<template>
  <el-form :model="tableForm" ref="formRef">
    <div style="margin-bottom: 25px"><span style="color:var(--color-danger);margin-right: 4px">*</span>备件列表：</div>
    <div style="margin-left: 10px">
      <el-table :data="tableForm.table" border :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}">
        <el-table-column type="index" label="序号" fixed width="50"></el-table-column>
        <el-table-column label="备件编号" width="220">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`table.${scope.$index}.c_number`">
              <el-input :value="scope.row.c_number" placeholder="备件编号" disabled></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="名称" width="220">
          <template slot-scope="scope">
            <el-form-item v-if="url==='inventories'" label-width="0" :prop="`table.${scope.$index}.c_name`"
                          :rules="{required: true, message: '备件名称必需', trigger: 'change'}">
              <el-autocomplete v-model="scope.row.c_name"
                               :fetch-suggestions="querySearchAsync" class="w-full"
                               placeholder="搜索备件名称" @select="(data)=>handleSelect(data,scope.$index)">
                <template #default="{ item }">
                  <div>备件编号：{{ item.c_number }}</div>
                  <span class="link">备件名称：{{ item.c_name }}</span>
                  <el-divider/>
                </template>
              </el-autocomplete>
            </el-form-item>
            <el-form-item v-else label-width="0" :prop="`table.${scope.$index}.name`"
                          :rules="{required: true, message: '备件名称必需', trigger: 'change'}">
              <el-autocomplete v-model="scope.row.name" :fetch-suggestions="querySearchAsync" class="w-full"
                               placeholder="搜索备件名称" @select="(data)=>handleSelect(data,scope.$index)">
                <template #default="{ item }">
                  <div>备件编号：{{ item.c_number }}</div>
                  <span class="link">备件名称：{{ item.name }}</span>
                  <el-divider/>
                </template>
              </el-autocomplete>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="url==='inventories'" label="库存数量" width="180">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`table.${scope.$index}.inventory`">
              <el-input :value="scope.row.inventory" placeholder="库存数量" disabled></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" width="220">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`table.${scope.$index}.model`">
              <el-input :value="scope.row.model" placeholder="备件规格" disabled></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="类别" width="220">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`table.${scope.$index}.type`">
              <el-input :value="scope.row.type" placeholder="型号" disabled></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="单位" width="220">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`table.${scope.$index}.uom`">
              <el-input :value="scope.row.uom" placeholder="备件单位" disabled></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="220">
          <template slot-scope="scope">
            <!--加入该form是为了resetFields能正确重置id-->
            <el-form-item :prop="`table.${scope.$index}.id`" style="display: none"></el-form-item>
            <el-form-item label-width="0" :prop="`table.${scope.$index}.quantity`"
                          :rules="rules">
              <el-input-number :min="0" :max="scope.row.inventory<9999?scope.row.inventory:9999" v-model="scope.row.quantity"
                               placeholder="入库数量"
                               type="number"></el-input-number>
            </el-form-item>

          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="80">
          <template slot-scope="scope">
            <el-link type="danger" style="font-size: 18px" icon="el-icon-delete"
                     :disabled="tableForm.table.length<=1 "
                     @click="delList(scope.$index)"></el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-btn" @click="addList" style="margin-top: 5px"><i class="el-icon-plus"></i></div>
    </div>

  </el-form>
</template>

<script>
export default {
  name: "editTable",
  props: {
    url: {
      type: String,
      default: 'inventories'
    },
    warehouseId: {
      default: ''
    }
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      if (value === '' || value == null) {
        callback(new Error('入库数量为必需'));
      } else if (value === 0) {
        callback(new Error('入库数量不能为零'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      tableForm: {
        table: [
          {
            id: null,
            c_name: null,
            c_number: null,
            model: null,
            type: null,
            uom: null,
            quantity: null,
            inventory: 0,
          }
        ]
      },
      rules: {validator: validateNumber, trigger: 'change'}
    }
  },
  watch: {
    'tableForm.table': {
      handler(current) {
        this.$emit('update:table', current)
      },
      deep: true
    },
    warehouseId() {
      this.$refs.formRef.resetFields()
      console.log(this.tableForm)
    },
  },
  methods: {
    //远程搜索获取设备
    querySearchAsync(query, cb) {
      if (!this.warehouseId && this.url === 'inventories') {
        cb([]);
        return this.$message.error('请先选择仓库')
      }
      query = query || ''
      this.$http.get(`/${this.url}?limit=10&keyword=${query}&warehouse_id=${this.warehouseId} `).then((res) => {
        let newData = [];
        res.data.data.forEach(item => {
          if (!this.tableForm.table.some(val => val.id == item.id)) newData.push(item) //选择备件时不允许选择重复的备件
        })
        if (this.url === "part_categories") newData = newData.filter(item => item.status === 1) //禁用的备件不允许入库
        cb(newData);
      });
    },
    /*选择备件*/
    handleSelect(data, index) {
      this.$set(this.tableForm.table, index, data)
      this.$set(this.tableForm.table[index], "quantity", 0)
    },

    addList() {
      this.tableForm.table.push(
        {
          c_number: null,
          id: null,
          model: null,
          type: null,
          uom: null,
          quantity: 0,
        }
      )
    },

    delList(index) {
      this.$confirm("是否确认删除？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableForm.table.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    validate() {
      let flag = false
      this.$refs.formRef.validate(valid => flag = valid)
      if (!this.tableForm.table.every(item => item.id != null)) {
        this.$message.error('存在备件未选择,请搜索名称选择备件')
        flag = false
      }
      return flag
    },

  }

}
</script>

<style scoped lang="scss">

.el-dialog:not(.ele-dialog-form) .el-dialog__body .el-form .el-form-item:last-child {
  margin-bottom: 0;
}

.add-btn {

  height: 57px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px dashed var(--color-primary);
  //letter-spacing:1rem;
  i {
    font-size: 18px;
    color: var(--color-primary);
    font-weight: bolder;
  }

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    cursor: pointer;
  }

  &:active {
    color: var(--color-primary-7);
    border-color: var(--color-primary-7);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  }
}


</style>

